import React, { useRef, useState } from "react";
import { request, useModel } from "@umijs/max";
import { create } from '@/services/swagger/interviewController';
import { Button, Card, Input, message, Space, Upload, UploadProps } from "antd";
import { getById } from "@/services/swagger/resumeController";
import { CodeOutlined, UploadOutlined } from "@ant-design/icons";
import {history} from "@umijs/max";
import { Row, Col } from 'antd';

const Create: React.FC = () => {
  const initialState = useModel("@@initialState");
  const currentUser = initialState.initialState?.currentUser;
  const [interviewVo, setInterviewVo] = useState<API.InterviewVo>({});
  const [resumeVo, setResumeVo] = useState<API.ResumeVo>({});
  const [uploadStatus, setUploadStatus] = useState<boolean>(false);
  const [interviewCreateRequest, setInterviewCreateRequest] = useState<API.InterviewCreateRequest>({
    userId: currentUser?.id || -1,
  });
  const [loading, setLoading] = useState<boolean>(false);

  const pollTimerRef = useRef<NodeJS.Timeout | null>(null);
  const count = useRef<number>(0);

  const props: UploadProps = {
    customRequest: async (options: any) => {
      const { file, onSuccess, onError, onProgress } = options;
      const formData = new FormData();
      formData.append('resume', file);

      try {
        const res = await request<API.BaseResponseLong>('/resume/upload', {
          method: 'POST',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data',
          },
          onUploadProgress: (event) => {
            if (event.total) {
              const percent = Math.floor((event.loaded / event.total) * 100);
              onProgress?.({ percent }, file);
            }
          },
        });
        onSuccess?.(res, file);
        message.success("简历上传成功");
        setUploadStatus(true);
        setResumeVo({ ...resumeVo, id: res.data }); // res.data 是 Long 类型 ID
      } catch (error) {
        onError?.(error);
        message.error('简历上传失败，请重试');
      }
    },
    onChange({ file }) {
      if (file.status === 'done') {
        console.log('上传完成，响应:', file.response);
      }
    },
    accept: '.pdf,.doc,.docx',
    showUploadList: false,
  };

  // 轮询函数
  const poll = async () => {
    if (!resumeVo.id || !currentUser?.id) return;

    try {
      const res = await getById({
        userId: currentUser.id,
        resumeId: resumeVo.id,
      });

      if (res.code === 0 && res.data !== null) {
        const updatedResume = {
          ...resumeVo,
          userId: currentUser.id,
          name: res.data.name,
          content: res.data.content,
          coverImg: res.data.coverImg,
        };
        setResumeVo(updatedResume);

        setInterviewCreateRequest(prev => ({
          ...prev,
          resumeId: resumeVo.id,
          resumeList: [res.data.content],
        }));

        stopPolling();
      } else {
        pollTimerRef.current = setTimeout(poll, 2000);
        count.current++;
        if (count.current >= 15) {
          // 建议增加到 15 次（30秒），原2次太短
          stopPolling();
          message.warning('简历处理超时，请稍后重试');
        }
      }
    } catch (error) {
      console.error('轮询出错:', error);
      message.error("系统错误");
      stopPolling();
    }
  };

  // 停止轮询
  const stopPolling = () => {
    if (pollTimerRef.current) {
      clearTimeout(pollTimerRef.current);
      pollTimerRef.current = null;
    }
    count.current = 0;
  };

  /**
   * 创建面试
   */
  const createInterview = async () => {
    if (!uploadStatus) {
      message.warning('请先上传简历');
      return;
    }
    if (!resumeVo.id) {
      message.error('简历ID缺失，请重新上传');
      return;
    }

    setLoading(true);
    try {
      await poll(); // 轮询直到拿到内容
      const res = await create(interviewCreateRequest);
      if (res.code === 0) {
        const newInterviewVo = res.data;
        setInterviewVo(newInterviewVo);
        message.success("创建成功");
        history.push(`/interview/start/${newInterviewVo.id}`);
      } else {
        message.error(res.message || "创建失败");
      }
    } catch (err) {
      message.error('创建过程中发生错误');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Row justify="center" style={{ padding: '24px 0' }}>
      <Col xs={24} sm={20} md={16} lg={12}>
        <Card
          title={<h2 style={{ margin: 0 }}>创建模拟面试</h2>}
          bordered={false}
          style={{ borderRadius: 8, boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}
        >
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            <div>
              <h3 style={{ fontWeight: 600, marginBottom: 8 }}>岗位名称</h3>
              <Input
                placeholder="请输入岗位名称"
                value={interviewCreateRequest.jobTitle}
                onChange={(e) => {
                  setInterviewCreateRequest((prev) => ({
                    ...prev,
                    jobTitle: e.target.value,
                  }));
                }}
              />
            </div>

            <div>
              <h3 style={{ fontWeight: 600, marginBottom: 8 }}>岗位职责</h3>
              <Input.TextArea
                placeholder="请输入岗位职责（建议详细描述）"
                rows={4}
                value={interviewCreateRequest.jobDesc}
                onChange={(e) => {
                  setInterviewCreateRequest((prev) => ({
                    ...prev,
                    jobDesc: e.target.value,
                  }));
                }}
              />
            </div>

            <div>
              <h3 style={{ fontWeight: 600, marginBottom: 8 }}>
                请上传您的简历（支持 .pdf / .doc / .docx）
              </h3>
              <p style={{ color: '#666', fontSize: 14, marginBottom: 8 }}>
                简历需包含可提取的文字内容，图片型 PDF 可能无法识别。
              </p>
              <Upload {...props}>
                <Button icon={<UploadOutlined />}>选择简历文件</Button>
              </Upload>
              {uploadStatus && (
                <p style={{ color: '#52c41a', marginTop: 8 }}>✓ 简历已上传，正在解析中...</p>
              )}
            </div>

            <div style={{ textAlign: 'center', marginTop: 16 }}>
              <Button
                type="primary"
                icon={<CodeOutlined />}
                onClick={createInterview}
                loading={loading}
                size="large"
                style={{ minWidth: 160 }}
              >
                {loading ? '创建中...' : '创建面试'}
              </Button>
            </div>
          </Space>
        </Card>
      </Col>
    </Row>
  );
};

export default Create;
